package com.jz.digital.utils;

import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;

import com.jz.digital.base.EditInputCallback;


public class PassWordInputFilter implements InputFilter {
    private EditInputCallback editInputCallback;
    public PassWordInputFilter(){
    }
    public PassWordInputFilter(EditInputCallback editInputCallback){
        this.editInputCallback = editInputCallback;
    }

    public void setEditInputCallback(EditInputCallback editInputCallback) {
        this.editInputCallback = editInputCallback;
    }
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (!valid(source, start, end)) return "";
        int lineCode1 = "_".codePointAt(0);
        int lineCode2 = "@".codePointAt(0);
        int lineCode3 = "#".codePointAt(0);
        int lineCode4 = "*".codePointAt(0);
        // 过滤掉表情符号
        String filteredText = source.toString().replaceAll("[^\\p{L}\\p{N}\\p{P}\\p{Z}]", "");
        int cp = Character.codePointAt(source, end - 1);
        if (isChinese(source.charAt(end-1)) || (!Character.isLetter(cp) && !Character.isDigit(cp) && lineCode1 != cp && lineCode2 != cp && lineCode3 != cp && lineCode4 != cp) || !filteredText.equals(source.toString())) {
            if(editInputCallback!=null) {
                editInputCallback.errorTip();
            }
            if (!filteredText.equals(source.toString())) {
                return filteredText;
            } else {
                return source.subSequence(0, end - 1).toString().replaceAll("[()（）\"“”]","");
            }
        }
        return source;
    }

    /**
     * 参数是否合法
     */
    private boolean valid(CharSequence text, int start, int end) {
        boolean success = true;
        if (TextUtils.isEmpty(text) || start < 0 || end < 0 || start >= end || start >= text.length() || end > text.length()) {
            success = false;
        }
        return success;
    }

    private boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
}
